package com.demo.service.impl;

import com.demo.common.Arith;
import com.demo.common.Constants;
import com.demo.dao.*;
import com.demo.entity.LadingBill;
import com.demo.service.ILadingBillLogService;
import com.demo.service.ILadingBillService;
import com.demo.service.IOrderService;
import com.demo.vo.LadingBillVo;
import com.demo.entity.LadingOrder;
import com.demo.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by byte2 on 2017-03-20.
 */
@Service
@Transactional
public class LadingBillServiceImpl implements ILadingBillService {
    @Autowired
    private ILadingBillDao dataDao;
    @Autowired
    private IOrderDao orderDao;
    @Autowired
    private IOfferDao offerDao;
    @Autowired
    private LadingOrderMapper ladingOrderDao;
    @Autowired
    private ISaleCommissionDao saleCommissionDao;
    @Autowired
    private ISalePersonAccountDao spaDao;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ILadingBillLogService lblService;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return dataDao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(LadingBill record) {
        record.setNo(Constants.generateServiceNO("T", Constants.generateLimitNumberStr(dataDao.queryCurrentDayCount() + 1, 4)));
        return dataDao.insert(record);
    }

    @Override
    public int insertSelective(LadingBill record) {
        record.setNo(Constants.generateServiceNO("T", Constants.generateLimitNumberStr(dataDao.queryCurrentDayCount() + 1, 4)));
        return dataDao.insertSelective(record);
    }

    /***
     * 创建提货订单：此方法只为后台用户创建提单使用
     * @param record 提单日志
     * @param isForce  是否强制执行完毕 true:是, false ：不是
     * @return
     */
    @Override
    public Object create(LadingBillVo record, Boolean isForce) {

        record.setNo(Constants.generateServiceNO("T", Constants.generateLimitNumberStr(dataDao.queryCurrentDayCount() + 1, 4)));
        record.setActual(0.0);
        if (isForce) {
            record.setActual(record.getNumberThisTime());
            record.setCheckStatus("1"); //
        }
        String orderId = record.getOrderIds().split(",")[0];
        Order order_ = orderDao.selectByPrimaryKey(Integer.valueOf(orderId));
        record.setClientele(order_.getClienteleName());
        record.setSaler(order_.getSaleName()); // 操作员
        Integer id = dataDao.insert(record);
        List<LadingOrder> loList = new ArrayList<LadingOrder>();
        if (record.getOrderIds() != null) {
            String[] orders = record.getOrderIds().split(",");
            String[] numbers = record.getNumbers().split(",");
            for (int i = 0; i < orders.length; i++) {
                LadingOrder lo = new LadingOrder();
                lo.setNumber(Double.valueOf(numbers[i]));
                if (isForce) {
                    lo.setActual(Double.valueOf(numbers[i]));
                }
                lo.setOrderId(orders[i]);
                lo.setLadingId(String.valueOf(record.getId()));
                loList.add(lo);
                Order order = new Order();
                order.setId(Integer.valueOf(orders[i]));
                Order res_order = orderDao.selectByPrimaryKey(Integer.valueOf(orders[i]));

                order.setDeliverNumber(Arith.add(Double.valueOf(numbers[i]), res_order.getDeliverNumber()));
                orderDao.updateByPrimaryKeySelective(order);
            }
            ladingOrderDao.addBatch(loList);
        }
        return id;
    }

//    public void giveActualCommission(String orderId) {
//        SaleCommission sc = new SaleCommission();
//        sc.setOrderId(orderId);
//        SaleCommission sc_res = saleCommissionDao.selectOneByOrderId(sc);
//        if (sc_res != null) {
//            sc_res.setStatus("1"); //1入账
//            SalePersonAccount spa = new SalePersonAccount();
//            SalePersonAccount spa_res = spaDao.selectBySaleID(sc_res.getSaleId());
//            spa_res.setCashWillReceiveTotal(Arith.sub(spa_res.getCashWillReceiveTotal(), sc_res.getCommission()));
//            spa_res.setCashCanWithDrawTotal(Arith.add(spa_res.getCashCanWithDrawTotal(), sc_res.getCommission()));
//            spaDao.updateByPrimaryKeySelective(spa_res);
//            saleCommissionDao.updateByPrimaryKeySelective(sc_res);
//            // todo：入账模板消息通知
//        }
//    }

    /***
     * 创建提货订单：此方法只为后台用户创建提单使用
     * @param record
     * @return
     */
    @Override
    public Object createBySp(LadingBill record) {
        record.setNo(Constants.generateServiceNO("T", Constants.generateLimitNumberStr(dataDao.queryCurrentDayCount() + 1, 4)));
        return dataDao.insertSelective(record);
    }

    @Override
    public Object checkSpLadingBill(LadingBill record) {
        LadingBill lb = dataDao.selectByPrimaryKey(record.getId());
        if (lb == null) {
            return "没有该提单参数相关数据，参数非法!";
        }

        if ("1".equals(record.getCheckStatus())) {

            Order order = new Order();
            order.setId(Integer.valueOf(record.getOrderId()));
            Order res_order = orderDao.selectByPrimaryKey(order.getId());
            if ((Arith.add(res_order.getDeliverNumber(), record.getNumberThisTime())) == res_order.getNumber()) {
                order.setDeliverStatus("1");
            } else if (Arith.add(res_order.getDeliverNumber(), record.getNumberThisTime()) < res_order.getNumber()) {
                order.setDeliverStatus("2");
            }
            record.setCheckStatus("1"); //后台操作直接审核通过
//            扣减报价交易中数量
//            Offer offer = offerDao.selectByPrimaryKey(Integer.valueOf(res_order.getOfferId()));
//            if (offer.getWithholdingNum() < record.getNumberThisTime()) {
//                return "报价交中数量小于本次提现数量，参数非法!";
//            }
//            Offer o = new Offer();
//            o.setWithholdingNum(offer.getWithholdingNum() - record.getNumberThisTime());
//            o.setDeductedNum(offer.getDeductedNum() + record.getNumberThisTime());
//            o.setId(offer.getId());
//            offerDao.updateByPrimaryKeySelective(o); // 更新报价中可售数量数据
            order.setDeliverNumber(Arith.add(record.getNumberThisTime(), res_order.getDeliverNumber()));
            orderDao.updateByPrimaryKeySelective(order);
        }
        return dataDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public LadingBill selectByPrimaryKey(Integer id) {
        return dataDao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(LadingBill record) {
        return dataDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(LadingBill record) {
        return dataDao.updateByPrimaryKey(record);
    }

    @Override
    public List<LadingBill> queryByPage(LadingBillVo arg) {
        return dataDao.queryByPage(arg);
    }

    @Override
    public int queryCount(LadingBillVo arg) {
        return dataDao.queryCount(arg);
    }

    @Override
    public Object update_labing_bill_actual(LadingOrder arg) {
        LadingOrder se_res = ladingOrderDao.selectByPrimaryKey(arg.getId());
        if (se_res.getActual() > 0) {
            return "提货单已经关闭，不能修改提货单!";
        }
        Order o = orderService.selectByPrimaryKey(Integer.valueOf(se_res.getOrderId()));
        if (!"0".equals(o.getStatus())) {
            return "订单已关闭,不能增加实提数量!";
        }
        arg.setActual(Arith.add(arg.getActual(), se_res.getActual()));
        int service_res = ladingOrderDao.updateByPrimaryKeySelective(arg);
        if (service_res > 0) {
            Order order = new Order();
            order.setActualNumber(arg.getActual());
            order.setId(Integer.valueOf(se_res.getOrderId()));
            order.setNumber(Arith.sub(se_res.getNumber(), arg.getActual()));
            Object obj = orderService.addActualNumber(order);
            if (obj instanceof Integer) {
                int res = Integer.valueOf(obj.toString());
                if (res == 0) {
                    throw new Error("修改实提数量错误");
                }
            }
        }
        LadingBill ladingBill = new LadingBill();
        LadingBill lb = dataDao.selectByPrimaryKey(Integer.valueOf(se_res.getLadingId()));
        ladingBill.setId(lb.getId());
        ladingBill.setActual(Arith.add(arg.getActual(), lb.getActual()));
        dataDao.updateByPrimaryKeySelective(ladingBill);
        return service_res;
    }


    @Override
    public int selectByStoreId(LadingBill record) {
        return dataDao.selectByStoreId(record);
    }
}
